<script setup>
import { ref, onMounted } from 'vue'
import { updateHomeworkService, getAllSubjects } from '@/api/homework.js'
import { ElMessage } from 'element-plus'
import useUserInfoStore from '@/stores/userInfo.js'
import throttle from 'lodash/throttle'
//老师管理作业
const userInfo = useUserInfoStore()
const subjects = ref([])
const total = ref(0)
const pageSize = ref(3)
const pageNum = ref(1)
const loading = ref(false)
const dialogVisible = ref(false)
const currentSubject = ref({
  id: null,
  title: '',
  content: '',
  createTime: '',
  grade: null,
  subjectName: ''
})

const subjectHomeworkList = async () => {
  loading.value = true
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    state: '已提交',
    teacherId: userInfo.info.id
  }
  try {
    let result = await getAllSubjects(params)
    console.log(result)
    if (
      result &&
      result.data &&
      Array.isArray(result.data.items) &&
      result.data.total !== undefined
    ) {
      subjects.value = result.data.items.map(item => ({
        ...item,
        grade: item.grade === null ? 0 : item.grade
      }))
      total.value = result.data.total
    } else {
      console.error('Unexpected data format:', result) // 这里的 debug 信息可以保留，便于开发时查看
      ElMessage.error('数据格式错误')
    }
  } catch (error) {
    ElMessage.error('获取作业列表失败')
    console.error(error) // 同样可以保留，便于开发时调试
  } finally {
    loading.value = false
  }
}

const gradeHomework = async (id, score) => {
  if (score === null || score === undefined || score === '') {
    ElMessage.error('评分不能为空')
    return
  }
  try {
    const response = await updateHomeworkService(id, score)
    if (response && response.code === 0) {
      ElMessage.success('评分成功')

      const subjectIndex = subjects.value.findIndex(
        subject => subject.id === id
      )
      if (subjectIndex !== -1) {
        subjects.value[subjectIndex].grade = score
      }

      closeDialog()
    } else {
      ElMessage.error(response.message || '评分更新失败')
    }
  } catch {
    ElMessage.error('评分失败')
  }
}

const openDialog = throttle(subject => {
  currentSubject.value = {
    ...subject,
    grade: subject.grade == null ? null : subject.grade
  }
  dialogVisible.value = true
}, 1000)

const closeDialog = () => {
  dialogVisible.value = false
  currentSubject.value = {
    id: null,
    title: '',
    content: '',
    createTime: '',
    grade: null,
    classname: null
  }
}
const enlargedImageUrl = ref('') // 用于放大查看的图片 URL
const isImageDialogVisible = ref(false) // 控制放大查看对话框的显示

const showEnlargedImage = url => {
  enlargedImageUrl.value = url
  isImageDialogVisible.value = true
}
onMounted(subjectHomeworkList)
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>作业评分</span>
      </div>
    </template>
    <el-table :data="subjects" style="width: 100%" :loading="loading">
      <el-table-column prop="title" label="作业标题"></el-table-column>
      <el-table-column prop="content" label="作业内容">
        <template #default="{ row }">
          <div v-html="row.content"></div>
        </template>
      </el-table-column>
      <el-table-column prop="subjectName" label="所属课程"></el-table-column>
      <el-table-column prop="createTime" label="提交时间"></el-table-column>
      <el-table-column label="图像">
        <template #default="{ row }">
          <div v-if="row?.coverImg" style="position: relative">
            <el-image
              :src="row.coverImg"
              alt="Cover Image"
              style="width: 100px; height: auto; cursor: pointer"
              @click="showEnlargedImage(row.coverImg)"
              fit="cover"
              :preview-src-list="[row.coverImg]"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="grade" label="评分"></el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="text" @click="openDialog(row)">批改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :total="total"
      layout="jumper, prev, pager, next"
      @size-change="subjectHomeworkList"
      @current-change="subjectHomeworkList"
    ></el-pagination>
    <el-dialog
      :title="currentSubject.id ? '编辑评分' : '添加评分'"
      v-model="dialogVisible"
      width="30%"
    >
      <el-form>
        <el-form-item label="作业标题">
          <el-input v-model="currentSubject.title" disabled></el-input>
        </el-form-item>
        <el-form-item label="作业内容">
          <el-input
            v-model="currentSubject.content"
            type="textarea"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="提交时间">
          <el-date-picker
            v-model="currentSubject.createTime"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            disabled
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="评分">
          <el-input-number v-model="currentSubject.grade"></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button
            type="primary"
            @click="gradeHomework(currentSubject.id, currentSubject.grade)"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
    <el-dialog
      title="查看图片"
      v-model:visible="isImageDialogVisible"
      width="50%"
    >
      <img :src="enlargedImageUrl" style="width: 100%; height: auto" alt="" />
    </el-dialog>
  </el-card>
</template>

<style scoped>
.page-container {
  margin: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header span {
  font-size: 18px;
  font-weight: bold;
}
</style>
